function buildDataCheckString(array $init_data): string {
ksort($init_data);
$data_check_array = [];
foreach ($init_data as $key => $val) {
$data_check_array[] = "{$key}={$val}";
}
return implode("\n", $data_check_array);
}
function verifyUser(string $init_data_string, string $bot_token): bool {
parse_str($init_data_string, $init_data);
if (
!isset($init_data['hash'])
or !isset($init_data['auth_date'])
or !isset($init_data['query_id'])
or !isset($init_data['user'])
) return false;
$hash = $init_data['hash'];
unset($init_data['hash']);
$data_check_string = buildDataCheckString($init_data);
$secret_key = hash_hmac('sha256', $bot_token, "WebAppData", true);
$secret_hash = hash_hmac('sha256', $data_check_string, $secret_key);
return $hash === $secret_hash;
}